﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ClassLibrary1
{
    public class BookStoreService
    {
        public BookStoreService(IStore store)
        {
            if (store == null)
                throw new ArgumentNullException("store");
            Store = store;
        }

        public IStore Store { get; protected set; }

        public int Count { get { return GetBooks().Count(); } }

        public List<string> GetAuthors()
        {
            return GetBooks().Select(b => b.Author).Distinct().ToList();
        }

        public List<string> GetTitles()
        {
            return GetBooks().Select(b => b.FormTitle()).Distinct().ToList();
        }

        public List<Book> FindByAuthor(string author)
        {
            return GetBooks().Where(b => b.Author == author).ToList();
        }

        public List<Book> FindByTitle(string title)
        {
            return GetBooks().Where(b => b.Title == title).ToList();
        }

        public IEnumerable<Book> GetBooks()
        {
            return Store.GetItems().OfType<Book>();
        }

        public void AddBook(Book book)
        {
            if (book == null)
                throw new ArgumentNullException("book");

            Store.AddItem(book);
        }

        public void Sell(Book book)
        {
            var books = GetBooks();
            if (books.Any(b => b == book))
                Store.Sell(book);
            else
                throw new Exception("Продаваемой книги нет.");

        }
    }
}